package 前缀和空间优化20250225;

import java.util.HashMap;

/**
 * 238.除自身外数组的乘积
 * https://leetcode.cn/problems/product-of-array-except-self/description/
 * @author
 * @version 1.0
 * @className ProductExceptSelf
 * @since 1.0
 */
public class ProductExceptSelf {
    /**
     * 前缀乘以后缀
     * 将前缀和后缀都用hashmap存储
     * @param nums
     * @return
     */
    public static int[] productExceptSelf(int[] nums) {
        //key是0-i，value是累计的乘积
        HashMap<Integer,Integer> mapPre = new HashMap<>();
        HashMap<Integer,Integer> mapEnd = new HashMap<>();
        //获取所有前缀
        int sum = 1;
        for (int i = 0; i < nums.length; i++) {
            sum=sum*nums[i];
            mapPre.put(i,sum);
        }
        for (int i = nums.length-1; i >= 0; i--) {
            sum=sum*nums[i];
            mapEnd.put(i,sum);
        }
        //循环数组，进行乘积
        for(int i=0;i<nums.length;i++){
            if(i==0){
                nums[i]=mapEnd.get(i+1);
            }else if(i== nums.length-1)
            {
                nums[i]=mapPre.get(i-1);
            }else {
                nums[i]=mapPre.get(i-1)*mapEnd.get(i+1);
            }
        }
        return nums;
    }
}
